<script setup>
import { ref } from 'vue'
import { artAddChannelServices, artEditChannelServices } from '@/api/article.js'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
const title = ref('')
//组件对外暴露一个open方法，基于open传参
// 如果传参有值 ，就代表是edit
// 如果没值，就代表是新增
// open调用后，打开对话框dialog
const open = (obj) => {
  console.log(obj)
  dialogVisible.value = true
  if (Object.keys(obj).length === 0) {
    title.value = '新增分类'
  } else {
    title.value = '编辑分类'
    cate.value = { ...obj }
  }
}

const cate = ref({
  cate_name: '',
  cate_alias: ''
})
const formRef = ref()
// 注册消息事件
const emit = defineEmits(['updateCate'])
const onSubmit = async () => {
  await formRef.value.validate()
  if (cate.value.id) {
    await artEditChannelServices(cate.value)
    ElMessage.success('修改成功')
  } else {
    ElMessage.success('新增成功')
    await artAddChannelServices(cate.value)
    cate.value = {
      cate_name: '',
      cate_alias: ''
    }
  }
  dialogVisible.value = false
  // 消息通知给父组件
  emit('updateCate')
}
// 向使用者暴露
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500" style="padding: 50px">
    <el-form ref="formRef" :model="cate" label-width="auto" style="max-width: 600px">
      <el-form-item label="分类名称" :rules="[{ required: true }]">
        <el-input v-model="cate.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" :required="true">
        <el-input v-model="cate.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
